package com.supor.aiot.common.helper;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;

import com.alipay.mobile.nebula.provider.H5AppProvider;
import com.alipay.mobile.nebula.util.H5Utils;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.mpaas.nebula.adapter.api.MPNebula;
import com.mpaas.nebula.adapter.api.MpaasNebulaInstallCallback;
import com.supor.aiot.common.app.AppAgent;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2021, by het, ShenZhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: TinyStartupHelper <br>
 * 作者: lei <br>
 * 日期: 2021/10/16 <br>
 */
public class TinyStartupHelper {
    private static final TinyStartupHelper ourInstance = new TinyStartupHelper();
    private Bundle tinyBundle;
    private String appId;
    private String query = "";

    public static TinyStartupHelper getInstance() {
        return ourInstance;
    }

    private TinyStartupHelper() {
        tinyBundle = new Bundle();
        tinyBundle.putBoolean("needAnimInTiny", true);
        tinyBundle.putString("transparentTitle", "always");
    }

    /**
     * 原生端启动小程序携带参数
     *
     * @param tinyAppId 小程序id
     * @param page 打开指定的小程序页面
     * @param params 后台配置的参数
     */
    public void startTiny(String tinyAppId, String page, String params) {
        startTiny(tinyAppId, page, "", params);
    }

    /**
     * 原生端启动小程序携带参数
     *
     * @param tinyAppId 小程序id
     * @param page 打开指定的小程序页面
     * @param redirectUrl 后台无法配置的参数，比如设备详细信息等, 设备详情页：{“pid”: “设备ID”, “mac”: “设备Mac地址或唯一码”}
     * @param params 后台配置的参数
     */
    public void startTiny(String tinyAppId, String page, String redirectUrl, String params) {
        AppAgent.tinyAppId = appId = tinyAppId;
        query = "";
        if (!TextUtils.isEmpty(redirectUrl)) {
            query = query + "redirectUrl=" + Uri.encode(redirectUrl.trim());
        }
        if (!TextUtils.isEmpty(params)) {
            query = query + "&" + params;
        }
        if (GlobalDataCache.userInfo != null) {
            query = query + "&userInfo=" + GsonUtil.getInstance().toJson(GlobalDataCache.userInfo);
        }
        if (query.startsWith("&")) {
            query = query.substring(1);
        }
        tinyBundle.putString("query",query); //设置参数
        if (!TextUtils.isEmpty(page)) {
            tinyBundle.putString("page", page + "?" + query);
        }
        Logc.d("page: " + page);
        Logc.d("startTiny: " + query);
        // MPNebula.startApp(tinyAppId, tinyBundle);
        AppAgent.tinyBundle = tinyBundle;
        try {
            downloadApp();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.getInstance().showCustomToast(e.getMessage());
        }
    }

    /**
     * 手动下载小程序
     */
    private void downloadApp() {
        H5AppProvider provider = H5Utils.getProvider(H5AppProvider.class.getName());
        if (provider == null) {
            startApp();
            return;
        }
        com.alipay.mobile.nebula.appcenter.model.AppInfo appInfo = provider.getAppInfo(appId);
        if (appInfo == null) {
            startApp();
        } else {
            Logc.i("downloadApp: appinfo: " + appInfo.toString());
            // 某版本应用离线包是否已经下载完成
            boolean isAvailable = provider.isAvailable(appId, appInfo.version);
            // 某版本应用是否已经安装
            boolean isInstalled = provider.isInstalled(appId, appInfo.version);
            Logc.d("downloadApp: isAvailable: " + isAvailable + ", isInstalled: " + isInstalled);
            if (isInstalled) {
                startApp();
            } else if (isAvailable) {
                installApp();
            } else {
                startApp();
            }
        }
    }

    /**
     * 手动安装小程序
     */
    private void installApp() {
        MPNebula.installApp(appId, new MpaasNebulaInstallCallback() {
            @Override
            public void onResult(boolean success, boolean isPatch) {
                super.onResult(success, isPatch);
                Logc.d("onResult: success: " + success + ", isPatch: " + isPatch);
                if (success) {
                    startApp();
                } else {
                    startApp();
                }
            }

            @Override
            public void onAppHasInstalled(String appId, String version) {
                super.onAppHasInstalled(appId, version);
                Logc.d("onAppHasInstalled: version: " + version);
                startApp();
            }
        });
    }

    private void startApp() {
        MPNebula.startApp(appId, tinyBundle);
    }

}
